/**
 * 数据库配置文件
 * @module config/database
 */

const { Sequelize } = require('sequelize');
const path = require('path');
require('dotenv').config();

// 获取数据库路径，默认为项目根目录下的database.sqlite
const dbPath = process.env.DB_PATH || path.join(__dirname, '../../database.sqlite');

/**
 * Sequelize实例
 * @type {Sequelize}
 */
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: dbPath,
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  define: {
    // 添加createdAt和updatedAt时间戳
    timestamps: true,
    // 使用下划线命名法
    underscored: true,
    // 禁用复数表名
    freezeTableName: true
  }
});

/**
 * 测试数据库连接
 * @returns {Promise<void>}
 */
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
    process.exit(1);
  }
};

module.exports = {
  sequelize,
  testConnection
}; 